﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Diagnostics;
using Young3.FMSearch.Core.Entities;
using Young3.FMSearch.Core.Attributes;
using Young3.FMSearch.Core.Entities.GameVersions;

namespace Young3.FMSearch.Core.Managers
{
    internal class GameManager
    {
        private bool fmLoaded;

        public GameManager()
        {
            fmLoaded = false;
        }

        public bool FMLoaded()
        {
            return fmLoaded;
        }

        public IVersion Version
        {
            get;
            private set;
        }

        /// <summary>
        /// Finds and loads the game in memory
        /// </summary>
        /// <returns>A bool indicating whether the game is running</returns>
        public bool CheckProcessAndGame()
        {
            FMProcess fmProcess = new FMProcess();
            Process[] fmProcesses = Process.GetProcessesByName("fm");
            Process[] wsmProcesses = Process.GetProcessesByName("wsm");
            
            if (fmProcesses.Length > 0 || wsmProcesses.Length > 0)
            {
                Process activeProcess;
                if (fmProcesses.Length > 0)
                    activeProcess = fmProcesses[0];
                else
                    activeProcess = wsmProcesses[0];

                fmProcess.Pointer = ProcessMemoryApi.OpenProcess(0x38, 1, (uint)activeProcess.Id);
                fmProcess.EndPoint = ProcessManager.GetProcessEndPoint(fmProcess.Pointer);
                fmProcess.Process = activeProcess;

                ProcessManager.fmProcess = fmProcess;

                fmProcess.VersionDescription = fmProcess.Process.MainModule.FileVersionInfo.ProductVersion;

                // search for the curr version
                foreach(var versionType in Assembly.GetCallingAssembly().GetTypes().Where(t=>typeof(IIVersion).IsAssignableFrom(t)))
                {
                    if (versionType.IsInterface) continue;

                    var instance = (IIVersion)Activator.CreateInstance(versionType);

                    if(instance.SupportsProcess(fmProcess))
                    {
                        Version = instance;
                        break;
                    }
                }

                if (Version == null)
                    throw new Exception("No supported version found");

                fmLoaded = true;
            }
            return fmLoaded;
        }
    }
}
